from rest_framework import filters
from rest_framework.exceptions import ValidationError

from apps.billing.models import Invoice


def invoice_filter(request, queryset):
    params = request.query_params

    if 'start_date' in params and 'end_date' in params:
        start_date = params['start_date']
        end_date = params['end_date']

        if start_date > end_date:
            raise ValidationError(
                'Start date must be lower than end date.')

        queryset = queryset.filter(created_at__date__range=[start_date, end_date])

    if 'status' in params:
        queryset = queryset.filter(status=params['status'])

    if 'provider_type' in params:
        provider_type = eval(params['provider_type'])
        queryset = queryset.filter(provider__provider_license__license_type__in=provider_type).distinct()

    return queryset